<?php

/**
 * @author Nguyen Thai Binh
 */
if (!defined('BASEPATH'))
  exit('No direct script access allowed');

class Generate extends CI_Controller {

  public function __construct() {
    parent::__construct();
    redirect('admin/index');
    exit;
  }

  public function index() {
    echo 'please select action';
  }

  protected function _list_field($table) {
    return $this->db->field_data($table);
  }

  protected function _list_table() {
    $sth = $this->db->query("SHOW TABLES");
    $tables = array();
    foreach ($sth->result_array() as $row) {
      $tables[] = end($row);
    }
    return $tables;
  }

  protected function _generate_controller($table) {
    $f = APPPATH . 'controllers/' . $table . EXT;
    @copy(APPPATH . 'temp/controller.tmp', $f);
    $lines = file($f);
    $out = '';
    foreach ($lines as $line) {
      if (strpos($line, 'Temp') !== false) {
        $out .= str_replace('Temp', strtoupper(substr($table, 0, 1)) . substr($table, 1), $line);
      } else {
        $out .= $line;
      }
    }
    $f = fopen($f, "w");
    fwrite($f, $out);
    fclose($f);
  }

  public function generate_controller($table = '') {
    $tables = $this->_list_table();
    if (!empty($table)) {
      if (in_array($table, $tables)) {
        $this->_generate_controller($table);
        echo 'ok';
      } else {
        show_error('invalid table name: ' . $table);
      }
    } else {
      foreach ($tables as $t) {
        $this->_generate_controller($t);
      }
      echo 'ok';
    }
  }
  
  protected function _generate_constants($table){
    $constants = "DB_TABLE_".strtoupper($table);
    if(!defined($constants)){
      $f = APPPATH .'config/constants'.EXT;
      $lines = file($f);
      $out = '';
      foreach ($lines as $line) {
        if (strpos($line, '/*define_table*/') !== false) {
          $out .= str_replace('/*define_table*/', 'define("DB_TABLE_'.strtoupper($table).'","'.
                  $table.'");'.chr(13).'/*define_table*/', $line);
        } else {
          $out .= $line;
        }
      }
      $f = fopen($f, "w");
      fwrite($f, $out);
      fclose($f);
    }
  }
  
  protected function _generate_autoload_model($table){    
    $f = APPPATH .'config/autoload'.EXT;
    $lines = file($f);
    $out = '';
    foreach ($lines as $line) {
      if (strpos($line, '/*model*/') !== false) {
        $out .= str_replace('/*model*/', '"'.$table.'_model",'.chr(13).' /*model*/', $line);
      } else {
        $out .= $line;
      }
    }
    $f = fopen($f, "w");
    fwrite($f, $out);
    fclose($f);
  }

  protected function _generate_model($table) {
    $this->_generate_constants($table);
    $f = APPPATH . 'models/' . $table.'_model'. EXT;
    @copy(APPPATH . 'temp/model.tmp', $f);
    $lines = file($f);
    $out = '';
    foreach ($lines as $line) {
      if (strpos($line, 'Temp') !== false) {
        $out .= str_replace('Temp', strtoupper(substr($table, 0, 1)) . substr($table, 1), $line);
      } else {
        $out .= $line;
      }
    }    
    $f = fopen($f, "w");
    fwrite($f, $out);
    fclose($f);
    $this->_generate_autoload_model($table);
  }

  public function generate_model($table = '') {
    $tables = $this->_list_table();
    if (!empty($table)) {
      if (in_array($table, $tables)) {
        $this->_generate_model($table);
        echo 'ok';
      } else {
        show_error('invalid table name: ' . $table);
      }
    } else {
      foreach ($tables as $t) {
        $this->_generate_model($t);
      }
      echo 'ok';
    }
  }
  
  protected function _generate_view_list($table, $f, $fields){
    $file = $f . '/_filter' . EXT;
    @copy(APPPATH . 'temp/view/_filter.tmp', $file);
    $file = $f . '/list' . EXT;
    @copy(APPPATH . 'temp/view/list.tmp', $file);
    $out = $html_title = $body = '';
    foreach ($fields as $field)
      if ($field->name != 'id') {
        $html_title .= '<th><?php echo $this->lang->line("label.' . $table . '.' . $field->name . '") ?></th>'.chr(13);
        $body .= '<td>'.chr(13);
        if(str_endsWith($field->name, '_id')){
          $ref_class = substr($field->name, 0, strpos($field->name, '_id'));
          $body .= '<?php'.chr(13).'
          $ref_obj = $this->'.$ref_class.'_model->get($obj["'.$field->name.'"]);'.chr(13).'
          if($ref_obj){ ?>'.chr(13).'
             <a href="<?php echo site_url("admin/'.$ref_class.'/show/".$obj["'.$field->name.'"])?>">'.chr(13).'
            <?php echo $this->'.$ref_class.'_model->to_string($ref_obj) ?></a>'.chr(13);
          $body .= '<?php } ?>'.chr(13);
          
        } else if(str_startsWith($field->name, 'is_')){
          $body .= '<?php echo empty($obj["'.$field->name.'"]) ? $this->lang->line("label.no") : $this->lang->line("label.yes") ?>';
        } else $body .= '<?php echo $obj["'.$field->name.'"] ?>'.chr(13);
        $body .= '</td>';
      }
    $lines = file($file);
    foreach ($lines as $line)
      if (strpos($line, '[title]') !== false) {
        $out .= str_replace('[title]', $html_title, $line);
      } else if (strpos($line, '[body]') !== false) {
        $out .= str_replace('[body]', $body, $line);
      } else $out .= $line;
    $file = fopen($file, "w"); fwrite($file, $out); fclose($file);
  }
  
  protected function _generate_view_form($table, $f, $fields){
    $file = $f . '/create' . EXT;
    @copy(APPPATH . 'temp/view/create.tmp', $file);
    $file = $f . '/edit' . EXT;
    @copy(APPPATH . 'temp/view/edit.tmp', $file);
    $file = $f . '/_form' . EXT;
    @copy(APPPATH . 'temp/view/_form.tmp', $file);
    $out = '';
    foreach ($fields as $field)
      if ($field->name != 'id') {
        $label = '<?php echo $this->lang->line(\'label.'. $table.'.'.$field->name.'\') ?>';
        if(str_endsWith($field->name, '_id')){
          $ref_class = substr($field->name, 0, strpos($field->name, '_id'));
          $input = '<select id="'.$field->name.'" name="'.$field->name.'" class="chzn chzn-done" style="visibility: visible;">
                <option value="0">
                  <?php echo $this->lang->line(\'label.option.select\')?>
                </option>
                <?php 
                  $ref_objs = $this->'.$ref_class.'_model->get_all();
                  foreach ($ref_objs as $ref) { ?>
                  <option value="<?php echo $ref["id"] ?>"
                    <?php echo empty($obj["'.$field->name.'"]) || $obj["'.$field->name.'"] != $ref["id"] ? "" : \'selected="selected"\' ?>>
                    <?php echo $this->'.$ref_class.'_model->to_string($ref) ?>
                  </option>
                <?php } ?>
              </select>';          
        } else if(str_startsWith($field->name, 'is_')){
          $input = '<input type="checkbox" id="'.$field->name.'" value="1" name="'.$field->name.'" 
            <?php echo isset($obj["'.$field->name.'"]) && $obj["'.$field->name.'"] ? \'checked="checked"\' : "" ?>>';
        } else if($field->type == 'text'){
          $input = '<br style="clear:both">
                    <textarea class="wysiwyg-advanced" rows="20" cols="40" name="'.$field->name.'" id="'.$field->name.'"
                              style="visibility: visible;"><?php echo empty($obj["'.$field->name.'"]) ? "" : $obj["'.$field->name.'"] ?></textarea>';
        } else {
          $input = '<input type="text" id="'.$field->name.'" value="<?php echo empty($obj["'.$field->name.'"]) ? "" : $obj["'.$field->name.'"] ?>" name="'.$field->name.'">'.chr(13);
        }
        
        $out .= '<li>
            <label for="'.$field->name.'">'.$label.'</label>
            <div class="input">'.$input.'</div>
          </li>';        
      }
    
    $file = fopen($file, "w"); fwrite($file, $out); fclose($file);
  }
    
  protected function _generate_view_show($table, $f, $fields){
    $file = $f . '/show' . EXT;
    @copy(APPPATH . 'temp/view/show.tmp', $file);
    $file = $f . '/_var' . EXT;
    @copy(APPPATH . 'temp/view/_var.tmp', $file);
    $out = '';
    foreach ($fields as $field)
      if ($field->name != 'id') {
        $label = '<?php echo $this->lang->line(\'label.'. $table.'.'.$field->name.'\') ?>';
        if(str_endsWith($field->name, '_id')){
          $ref_class = substr($field->name, 0, strpos($field->name, '_id'));
          $body = '<?php'.chr(13).'
          $ref_obj = $this->'.$ref_class.'_model->get($obj["'.$field->name.'"]);'.chr(13).'
          if($ref_obj){ ?>'.chr(13).'
             <a href="<?php echo site_url("admin/'.$ref_class.'/show/".$obj["'.$field->name.'"])?>">'.chr(13).'
            <?php echo $this->'.$ref_class.'_model->to_string($ref_obj) ?></a>'.chr(13);
          $body .= '<?php } ?>'.chr(13);
          
        } else if(str_startsWith($field->name, 'is_')){
          $body = '<?php echo empty($obj["'.$field->name.'"]) ? $this->lang->line("label.no") : $this->lang->line("label.yes") ?>';
        } else $body = '<?php echo $obj["'.$field->name.'"] ?>'.chr(13);
        
        $out .= '<li>
            <label for="'.$field->name.'">'.$label.'</label>
            <div class="input">'.$body.'</div>
          </li>';        
      }
    
    $file = fopen($file, "w"); fwrite($file, $out); fclose($file);
  }
  

  protected function _generate_view($table) {
    $fields = $this->_list_field($table);
    $f = APPPATH . 'views/admin/' . $table;
    @mkdir($f);
    $this->_generate_view_list($table, $f, $fields);
    $this->_generate_view_form($table, $f, $fields);
    $this->_generate_view_show($table, $f, $fields);
  }

  public function generate_view($table = '') {
    $tables = $this->_list_table();
    if (!empty($table)) {
      if (in_array($table, $tables)) {
        $this->_generate_view($table);
        echo 'ok';
      } else {
        show_error('invalid table name: ' . $table);
      }
    } else {
      foreach ($tables as $t) {
        $this->_generate_view($t);
      }
      echo 'ok';
    }
  }
  
  public function generate_all($table = ''){
    $this->generate_controller($table);
    $this->generate_model($table);
    $this->generate_view($table);
  }

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */